package com.zju.searchEngine.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.zju.searchEngine.model.Index;
import com.zju.searchEngine.model.WebPage;
import com.zju.searchEngine.service.IIndexService;
import com.zju.searchEngine.service.IWebPageService;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Controller
public class SearchEngineController {

	@Autowired
	private IIndexService indexService;
	@Autowired
	private IWebPageService webPageService;

	@RequestMapping("/getIndexByKeyWords")
	public void getIndexByKeyWords(HttpServletResponse resp, HttpServletRequest req)
			throws UnsupportedEncodingException {
		req.setCharacterEncoding("utf-8");
		resp.setContentType("text/html;charset=utf-8");
		resp.setCharacterEncoding("UTF-8");

		String keyWordStr = req.getParameter("keyWords");
		System.out.println(keyWordStr);// 输出搜索关键字
		String[] keyWords = keyWordStr.split(" ");
		List<String> keyIndexList = new ArrayList<String>();
		JSONArray json = new JSONArray();

		for (String keyWord : keyWords) {
			List<Index> indexList = new ArrayList<Index>();
			StringBuilder result = new StringBuilder();
			if (!"".equals(keyWord)) {
				indexList = indexService.selectByKeyWordLike("%" + keyWord + "%");
				if (indexList.size() > 0) {
					for (int i = 0; i < indexList.get(0).getKeyindex().length(); i++) {
						result.append("0");
					}
					String res = result.toString();
					for (Index index : indexList) {
						res = or(res, index.getKeyindex());
					}
					keyIndexList.add(res);
				}
			}
		}
		

		if (keyIndexList.size() > 0) {// 如果关键字存在
			String indexResult = "";
			if(keyIndexList.size()<keyWords.length){
				for (int i = 0; i < keyIndexList.get(0).length(); i++) {
					indexResult += "0";
				}
			}else{
				if (keyIndexList.size() == 1) {
					indexResult = keyIndexList.get(0);
				} else {
					indexResult = getIndexAndResult(keyIndexList);// 获取索引结果
				}
			}
			char[] indexResults = indexResult.toCharArray();
			// 根据获取的索引结果，找到需要的网页
			for (int i = 0; i < indexResults.length; i++) {
				if (indexResults[i] == '1') {
					WebPage webPage = webPageService.selectById(i + 1);
					// webPages.add(webPage);
					JSONObject jo = new JSONObject();
					jo.put("id", webPage.getId());
					jo.put("pageName", webPage.getPagename());
					jo.put("url", webPage.getUrl());
					json.add(jo);
					System.out.println("搜索到的网页为=" + webPageService.selectById(i + 1).getPagename());
				}
			}
			try {
				PrintWriter out = resp.getWriter();
				out.write(json.toString());
				out.flush();
				out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
				
		} else {
			System.out.println("未搜索到任何结果");
			try {
				PrintWriter out = resp.getWriter();
				out.write("未搜索到任何结果");
				out.flush();
				out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

	}

	private String and(String str1, String str2) {
		StringBuilder res = new StringBuilder();
		int min = Math.min(str1.length(), str2.length());
		int i = 0;
		for (i = 0; i < min; i++) {
			int c = str1.charAt(i) & str2.charAt(i);
			res.append(c - 48);
		}

		return res.toString();
	}

	private String or(String str1, String str2) {
		StringBuilder res = new StringBuilder();
		int min = Math.min(str1.length(), str2.length());
		int i = 0;
		for (i = 0; i < min; i++) {
			int c = str1.charAt(i) | str2.charAt(i);
			res.append(c - 48);
		}

		if (i < str1.length())
			res.append(str1.substring(i));

		if (i < str2.length())
			res.append(str2.substring(i));

		return res.toString();
	}

	/*
	 * 求索引的或
	 */
	private String getIndexOrResult(List<String> keyIndexList) {
		int n = keyIndexList.get(0).length();
		char[] indexResult = new char[n];
		for (int i = 0; i < n; i++) {
			indexResult[i] = '1';
		}
		for (int i = 0; i < keyIndexList.size(); i++) {
			char[] indexs = keyIndexList.get(i).toCharArray();
			for (int j = 0; j < indexs.length; j++) {
				if (indexs[j] == '0') {
					indexResult[j] = '0';
				}
			}
		}
		return new String(indexResult);
	}

	private String getIndexAndResult(List<String> keyIndexList) {
		StringBuilder result = new StringBuilder();
		String res = "";
		if (keyIndexList.size() > 0) {
			for (int i = 0; i < keyIndexList.get(0).length(); i++) {
				result.append("1");
			}
			res = result.toString();
			for (String index : keyIndexList) {
				res = and(res, index);
			}
		}

		return res;
	}
}